<template>
    <div>
        <a-icon
                v-if="collapsed"
                type="menu-unfold"
                @click="expandSidebar"
                style="position: fixed;left: 10px;top: 2px;font-size: 30px;color:rgba(255, 255, 255, 0.65);"
        />
        <a-layout>
            <a-layout-sider class="file-browse-sider " :width="sidebarWidth">
                <file-browse
                        ref="fileBrowse"
                        :extendWidth="sidebarWidth"
                        :collapsedWidth="0"
                        @collapse="onFileBrowseCollapse"
                        @fileSelect="onFileSelect"
                >
                </file-browse>
            </a-layout-sider>
            <a-layout-content :style="{ marginLeft: sidebarWidth+'px' }">
                <a-spin :spinning="spinning">
                    <div v-if="isOpenFile"
                         class="edit-box"
                         tabindex="-1">
                        <div v-if="isMarkdown" class="editor-main content-height">
                            <le-editor
                                    v-model="value"
                                    :hljs-css="hljsCss"
                                    :image-uploader="imageUploader"
                                    @save="save"
                                    theme="railscasts"
                            ></le-editor>
                        </div>
                        <div class="text-main content-height" v-else>
                            <a-textarea v-model="value" style="height: 100%;resize: none;"></a-textarea>
                        </div>
                    </div>
                </a-spin>
            </a-layout-content>
        </a-layout>

    </div>
</template>
<script>
    import FileBrowse from '../components/FileBrowse'
    import ALayoutSider from "ant-design-vue/es/layout/Sider";
    import {getProperty} from '../utils/config'
    import fs from 'fs'
    import ATextarea from "ant-design-vue/es/input/TextArea";
    import {getFileExt, saveFile} from '../utils/fileUtil'
    import $ from 'jquery'

    export default {
        components: {
            ATextarea,
            ALayoutSider,
            FileBrowse
        },
        data() {
            return {
                filePath: '',
                mdLimitSize: 100 * 1024,
                textLimitSize: 1024 * 1024,
                collapsed: false,
                sidebarWidth: 350,
                hljsCss: 'agate',
                value: '',
                isChange: false,
                // 自定义
                imageUploader: {
                    custom: false,
                    fileType: 'file',
                    fileNameType: '',
                    imagePrefix: 'http://47.100.125.98', // 图片上传成功后，预览地址前缀
                    type: 'server',
                    url: 'http://47.100.125.98:82/upload' // 上传接口地址
                },
                spinning: false,
                isMarkdown: true,
                isOpenFile: false,
                ignoreValueWatch: true,
                enableAutoDelaySave: true,
                autoDelaySaveInterval: 2,
                delaySaveTimer: null,

            }
        },
        watch: {
            value(val, oldVal) {
                //当文件加载时会额外触发内容修改监听，通过ignoreValueWatch忽略
                if (this.ignoreValueWatch)
                    return this.ignoreValueWatch = false
                this.isChange = true;
            }
        },
        methods: {
            // 自定义图片上传
            // uploadImg: function ($vm, file, fileName) {
            //   console.log($vm)
            //   console.log(file)
            //   console.log(fileName)
            //   // 添加图片
            //   // 两个参数 第一个是图片访问路径 第二个是文件名
            //   $vm.insertImg(`${$vm.config.imageUploader.imagePrefix}${fileName}`, fileName)
            // },
            save: function (val) {
                // 获取预览文本
                console.log(this.value) // 这里是原markdown文本
                console.log(val) // 这个是解析出的html
                this.saveFile()
            },
            saveFile: function () {
                if (!this.isChange) return
                this.isChange = false
                if (this.filePath) {
                    saveFile(this.filePath, this.value)
                    console.log(`文件${this.filePath}保存了一次`)
                }
            },
            onFileBrowseCollapse(width) {
                this.sidebarWidth = width;
                this.collapsed = width == 0 ? true : false;
            },
            expandSidebar() {
                this.$refs.fileBrowse.expand()
            },
            //打开文件
            onFileSelect(path) {
                this.filePath = path
                console.log(this.filePath)
                //保存文件
                this.saveFile()
                //打开新文件
                this.loadFile(this.filePath)
            },
            //加载文件
            loadFile(path) {
                this.ignoreValueWatch = true
                this.value = ""
                if (!path) {
                    return this.isOpenFile = false
                }
                this.isOpenFile = true
                let ext = getFileExt(path).toLowerCase()
                this.isMarkdown = (ext == "md" || ext == "markdown")
                fs.stat(path, (err, stats) => {
                    if (err) {
                        console.error(err)
                        return this.$message.error("文件打开失败")
                    }
                    if (stats.size > (this.isMarkdown ? this.mdLimitSize : this.textLimitSize)) {
                        return this.$message.warn("文件大小超过限制，无法打开");
                    }
                    this.spinning = true
                    fs.readFile(path, 'utf-8', (err, data) => {
                        this.spinning = false
                        if (err) {
                            switch (err.code) {
                                case 'EACCES':
                                    return this.$message.error("文件访问被拒绝")
                                case "EISDIR":
                                    return this.$message.error("当前路径异常")
                                default:
                                    return this.$message.error("文件打开失败")
                            }
                        }
                        this.ignoreValueWatch = true
                        this.value = data
                    });

                })
            },
            //编辑区聚焦
            onEditBoxFocus() {
            },
            //编辑区失焦
            onEditBoxBlur() {
                this.saveFile();
            }
        },
        created() {
            let mdLimit = getProperty("mdLimitSize")
            let textLimit = getProperty("textLimitSize")
            if (typeof mdLimit === 'number' && mdLimit > 0) {
                this.mdLimitSize = mdLimit
            }
            if (typeof textLimit === 'number' && textLimit > 0) {
                this.textLimitSize = textLimit
            }

            this.enableAutoDelaySave = getProperty("enableAutoDelaySave")
            this.autoDelaySaveInterval = getProperty("autoDelaySaveInterval")
        },
        mounted() {
            //定时自动保存
            if (this.enableAutoDelaySave) {
                setInterval(() => {
                        this.saveFile()
                    },
                    this.autoDelaySaveInterval * 1000)
            }

            //绑定编辑框失去焦点自动保存事件
            $(document)
                .on('focus', '.edit-box', () => {
                    this.onEditBoxFocus()
                })
                .on('blur', '.edit-box', () => {
                    this.onEditBoxBlur()
                });

        }
    }

</script>

<style scoped>

    .file-browse-sider {
        height: calc(100% - 36px);
        background: white;
        position: fixed;
        overflow: hidden;
    }

    .editor-main, .text-main {
        color: #2c3e50;
        width: 100%;
    }

    .editor-main /deep/ .markdown-body,
    .editor-main /deep/ .le-editor-right .markdown-body {
        overflow-y: auto;
    }

    .editor-main /deep/ .le-editor-tools > li {
        padding: 2px;
    }

    .text-main /deep/ .ant-input {
        border: 0;
        font-size: 16px;
        color: black;
    }

    .text-main > .ant-input::-webkit-scrollbar {
        width: 8px;
        height: 4px;
    }

    .text-main > .ant-input::-webkit-scrollbar-button {
        width: 8px;
        height: 0;
    }

    .text-main > .ant-input::-webkit-scrollbar-thumb {
        background: #cfd6d6;
        -webkit-transition: .3s;
        transition: .3s;
        border-radius: 5px;
    }

    .text-main > .ant-input::-webkit-scrollbar-track {
        background: 0 0;
    }

</style>
